package com.xxxcompany.shop.dao.impl;

import java.sql.*;

import com.xxxcompany.shop.dao.IUserDAO;
import com.xxxcompany.shop.entity.User;
import com.xxxcompany.utils.DbUtils;

public class UserDAOImpl implements IUserDAO {

	@Override
	public User find(String username, String password) throws SQLException {

		// 1. 获取连接
		Connection conn = DbUtils.getConnection();
		String sql = "select * from user where username = ? and password = ?";
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, username);
		stmt.setString(2, password);
		ResultSet rs = stmt.executeQuery();

		User result = null;
		// 遍历结果集，封装结果信息
		if (rs.next()) {
			result = new User(username, password);
		}
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, rs);
		return result;
	}

	@Override
	public int insert(User u) throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = DbUtils.getConnection();
		Statement stmt = conn.createStatement();

		// 3. 执行查询
		String sql = "insert into user value(null,'" + u.getUsername() + "','" + u.getPassword() + "')";
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

}
